import React, { useEffect, useState, useRef } from 'react';
import { Form, Row, Input, Select, DatePicker, Card, Button, Col, Tag } from 'antd';
import { connect } from 'umi';
import { history } from 'umi';
import moment from 'moment';
import { getOrganization } from '@/utils/utils';

import request from '@/utils/request';
import pageTabUtil from '@/utils/pageTabUtil';
import { SelectForm, FormContainer, SearchInput, RadioForm, TreeSelectForm } from '@/components/UserForm';
// import useTreeSelectData from '@/hooks/useTreeSelectData';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { withRoutePage } from '@/utils/enhanceUtils';
import { getServicePersonlist } from '@/services/attendance/overtime';
import { getTypeList } from '@/services/components/userform';
import { dictionaryList } from '@/services/dictionary';
// import authHelper from '@/utils/auth/helper';
import { getPostListByCondition } from '@/services/flowMine/apply';
import styles from './AddEntry.less';

// const { checkCode } = authHelper;
const { Option } = Select;

const formItemLayout = {
    labelCol: {
        md: { span: 8 },
        xs: { span: 24 },
        sm: { span: 24 }
    },
    wrapperCol: {
        md: { span: 14 },
        xs: { span: 24 },
        sm: { span: 24 }
    }
};

const AddEntry = ({ form, entryDetail, location, dispatch, loading }) => {
    const { getFieldDecorator } = form;
    const { detail = {} } = entryDetail;
    const { companyId } = detail;
    const {
        query: { action, offerCode }
    } = location;
    const [exceedDays, setExceedDays] = useState(0);
    const [workNatureName, setWorkNatureName] = useState('');
    const [selectDepartmentId, setSelectDepartmentId] = React.useState('');
    const [showEntryHelpMsg, setShowEntryHelpMsg] = React.useState(false);
    // const [detailLoaded, setDetailLoaded] = React.useState(false);
    const companyRef = useRef({ companyId });
    if (companyId !== companyRef.current.companyId) {
        companyRef.current = { companyId };
    }

    // 入职 or 详细
    let editStatus = false;
    if (action === 'edit') {
        editStatus = true;
    }

    const handleSubmit = e => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (!err) {
                const payload = {
                    ...values,
                    offerCode: detail.offerCode,
                    candidateCode: detail.candidateCode,
                    entryDate: values.entryDate.format('YYYY-MM-DD'),
                    employeeName: detail.employeeName,
                    sex: values.sex,
                    employeeRank: detail.employeeRank,
                    id: detail.id,
                    highestDegree: detail.highestDegree,
                    birthday: typeof detail.birthday === 'object' ? '' : detail.birthday,
                    companyId: detail.companyId
                };
                dispatch({
                    type: 'entryDetail/saveEntry',
                    payload,
                    callback: () => {
                        const { pathname } = location;
                        const redirectPath =
                            pathname === '/personal/portal/myOnboardAndLeave/addEntry'
                                ? '/personal/portal/myOnboardAndLeave/myEntryManagement'
                                : '/office/personnelManagement/onboardAndLeave/entryManagement';
                        history.push(redirectPath);
                    }
                });
            }
        });
    };

    const regionMap = {
        100: '集团',
        101: '厦门',
        102: '新加坡'
    };

    // 页面离开的时候，把详情内容清空
    useEffect(
        () => () => {
            dispatch({
                type: 'entryDetail/save',
                payload: { detail: {} }
            });
        },
        []
    );

    useEffect(() => {
        if (!offerCode) return;

        if (editStatus) {
            dispatch({
                type: 'entryDetail/getOfferDetail',
                payload: { offerCode }
            });
            return;
        }

        dispatch({
            type: 'entryDetail/getEntryDetail',
            payload: { offerCode }
        });
    }, [editStatus, offerCode]);

    useEffect(() => {
        if (editStatus || getOrganization(detail.companyId)?.area === 'cn' || !detail.workNature) return;
        getTypeList({ dictCode: 'jobType' }).then(res => {
            if (res && res.code === 10000 && res.data) {
                const dictObj = res.data.find(item => item.dictValue === detail.workNature);
                if (dictObj) setWorkNatureName(dictObj.dictName);
            }
        });
    }, [detail.workNature]);

    useEffect(() => {
        const diff = moment().diff(moment(form.getFieldValue('entryDate')), 'days');
        // if (diff > 0) setExceedDays(diff);
        setExceedDays(diff);
    }, [form.getFieldValue('entryDate')]);

    useEffect(() => {
        if (detail.departmentId) {
            setSelectDepartmentId(detail.departmentId);
        }
    }, [detail]);

    const getEntryHelpMsg = () => (
        <>
            <div style={{ fontSize: 12 }}>
                如无相关职位，,请前往
                <a
                    onClick={() => {
                        const path = '/office/personnelManagement/organization/employeeList';
                        pageTabUtil.openTab(path);
                        history.push(path);
                    }}
                >
                    组织管理
                </a>
                设置
            </div>
        </>
    );

    const renderOfferContent = () => (
        <Form {...formItemLayout} onSubmit={handleSubmit}>
            <FormContainer>
                <Form.Item label="员工姓名">{detail.employeeName}&nbsp;</Form.Item>
                <Form.Item label="性别">
                    {getFieldDecorator('sex', {
                        initialValue: detail.sex,
                        rules: [
                            {
                                required: true,
                                message: '请选择性别'
                            }
                        ]
                    })(
                        <RadioForm
                            params={{ dictCode: 'sexType' }}
                            requireParam={['dictCode']}
                            getData={params =>
                                getTypeList(params).then(res => {
                                    if (res && res.code === 10000 && res.data) {
                                        return res.data || [];
                                    }
                                    return [];
                                })
                            }
                            fieldsName={{
                                radioValue: 'dictValue',
                                radioTitle: 'dictName'
                            }}
                            radioProps={{
                                placeholder: ''
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="手机号">
                    {getFieldDecorator('mobile', {
                        initialValue: detail.mobile || '',
                        rules: [
                            {
                                required: true,
                                validator(rule, value, callback) {
                                    const regex = /^\d{7,11}$/;
                                    if (!value) {
                                        callback('手机号不能为空');
                                    } else if (!regex.test(value)) {
                                        callback('只能输入7-11位数字');
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(
                        <Input
                            addonBefore={getFieldDecorator('areaCode', {
                                initialValue: getOrganization(detail.companyId)?.area === 'cn' ? '86' : '65'
                            })(
                                <Select style={{ width: 70 }}>
                                    <Option value="86">+86</Option>
                                    <Option value="65">+65</Option>
                                </Select>
                            )}
                        />
                    )}
                </Form.Item>
                <Form.Item label="入职日期">
                    {getFieldDecorator('entryDate', {
                        initialValue: moment(detail.entryDate),
                        rules: [
                            {
                                required: true,
                                message: '请输入入职日期'
                            }
                        ]
                    })(<DatePicker style={{ width: '100%' }} />)}
                    {exceedDays > 0 && (
                        <div className={styles.exceedDays}>
                            <span>已超期限{exceedDays}天</span>
                        </div>
                    )}
                </Form.Item>
                <Form.Item label="所属公司">{detail.companyName}&nbsp;</Form.Item>
                <Form.Item label="用户名">
                    {getFieldDecorator('userName', {
                        rules: [
                            {
                                required: true,
                                message: '用户名不能为空'
                            },
                            {
                                pattern: /^[a-zA-Z,_-\s]{1,}$/,
                                message: '只限定输入英文字符'
                            },
                            {
                                min: 2,
                                max: 50,
                                message: '用户名字数范围:2到50个字符'
                            }
                        ]
                    })(<Input placeholder="2-50个英文字符" />)}
                </Form.Item>
                <Form.Item label="部门">
                    {getFieldDecorator('departmentId', {
                        initialValue: detail.departmentId
                    })(
                        <TreeSelectForm
                            params={{
                                companyId: detail.companyId
                            }}
                            requireParam={['companyId']}
                            getData={params =>
                                request('/api/org/v1/functional/list', {
                                    params
                                }).then(res => {
                                    if (res && res.code === 10000 && res.data) {
                                        return res.data || [];
                                    }
                                    return [];
                                })
                            }
                            fieldsName={{
                                value: 'id',
                                title: 'departmentName'
                            }}
                            Props={{
                                placeholder: '请选择部门',
                                showArrow: true
                            }}
                            onChange={v => {
                                setSelectDepartmentId(v);
                                form.resetFields(['postId', 'postGradeCode']);
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="员工邮箱">
                    {getFieldDecorator('email', {
                        rules: [
                            {
                                type: 'email',
                                message: '请输入正确格式的邮箱！'
                            },
                            {
                                required: true,
                                message: '请输入邮箱！'
                            }
                        ]
                    })(<Input placeholder="请输入邮箱" />)}
                </Form.Item>
                <Form.Item label="带教人">
                    {getFieldDecorator('teacherId', {
                        initialValue: detail.teacherId || undefined, // 默认值如果为空字符串的话会影响placeholder展示
                        rules: [
                            {
                                required: true,
                                message: '带教人不能为空'
                            }
                        ]
                    })(
                        <SearchInput
                            params={{
                                companyId: detail.companyId
                            }}
                            requireParam={['companyId']}
                            getData={params =>
                                getServicePersonlist(params).then(res => {
                                    if (res && res.code === 10000) {
                                        return res.data || [];
                                    }
                                    return [];
                                })
                            }
                            selectProps={{
                                placeholder: '请输入带教人姓名',
                                allowClear: true
                            }}
                            fieldsName={{
                                value: 'id',
                                title: 'employeeName',
                                extraParams: 'userName'
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="角色">
                    {getFieldDecorator('roles', {
                        initialValue: [],
                        rules: [
                            {
                                required: true,
                                message: '请选择角色'
                            }
                        ]
                    })(
                        <SelectForm
                            params={{
                                companyId: detail.companyId
                            }}
                            requireParam={['companyId']}
                            getData={() =>
                                request(`/api/oa/v1/role/getallrole/${detail.companyId}`).then(res => {
                                    if (res && res.code === 10000 && res.data) {
                                        return res.data || [];
                                    }
                                    return [];
                                })
                            }
                            fieldsName={{
                                selectValue: 'id',
                                selectTitle: 'roleName'
                            }}
                            selectProps={{
                                showArrow: false,
                                mode: 'multiple',
                                placeholder: '请选择角色',
                                dropdownRender: menu => <div>{menu}</div>
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="招聘职位">{detail.entryPostName}</Form.Item>
                <Form.Item label="招聘职级">{detail.employeeRank}</Form.Item>
                <Form.Item label="入职职位" help={showEntryHelpMsg ? getEntryHelpMsg() : ''}>
                    {getFieldDecorator('postId', {
                        initialValue: undefined,
                        rules: [
                            {
                                required: true,
                                message: '职位不能为空'
                            }
                        ]
                    })(
                        <SelectForm
                            params={{
                                departmentId: selectDepartmentId
                            }}
                            onChange={(_, params) => {
                                form.resetFields('postGradeCode');
                                if (params && params.props && params.props.postGradeCode) {
                                    form.setFieldsValue({
                                        postGradeCode: params.props.postGradeCode
                                    });
                                }
                            }}
                            getData={params => {
                                console.log(detail && detail.departmentId, 'detail && detail.departmentId');
                                if (detail && detail.departmentId) {
                                    return getPostListByCondition(params).then(res => {
                                        if (res && res.code === 10000 && res.data) {
                                            if (res.data.length === 0) {
                                                setShowEntryHelpMsg(true);
                                            } else {
                                                setShowEntryHelpMsg(false);
                                            }
                                            return res.data || [];
                                        }
                                        return [];
                                    });
                                }
                                return [];
                            }}
                            fieldsName={{
                                selectValue: 'id',
                                selectTitle: 'postName'
                            }}
                            selectProps={{
                                placeholder: '请选择职位',
                                allowClear: true
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="入职职级">
                    {getFieldDecorator('postGradeCode', { initialValue: detail.postGradeCode })(
                        <Input placeholder="根据入职职位自动获取" disabled />
                    )}
                </Form.Item>
                <Form.Item label="工作性质：">
                    {getFieldDecorator('workNature', {
                        initialValue: detail.workNature,
                        rules: [
                            {
                                required: true,
                                message: '请选择工作性质'
                            }
                        ]
                    })(
                        <SelectForm
                            params={{
                                dictCode: getOrganization(detail.companyId)?.area === 'cn' ? 'jobNature' : 'jobType'
                            }}
                            requireParam={['dictCode']}
                            getData={params =>
                                getTypeList(params).then(res => {
                                    if (res && res.code === 10000 && res.data) {
                                        return res.data || [];
                                    }
                                    return [];
                                })
                            }
                            fieldsName={{
                                selectValue: 'dictValue',
                                selectTitle: 'dictName'
                            }}
                            selectProps={{ placeholder: '请选择工作性质' }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="试用期">
                    {getFieldDecorator('tryDuration', {
                        initialValue: detail.tryDuration,
                        rules: [
                            {
                                required: true,
                                message: '试用期不能为空'
                            },
                            {
                                min: 2,
                                max: 50,
                                message: '请输入2~50个字符'
                            }
                        ]
                    })(
                        <SelectForm
                            params={{ code: 'tryDuration' }}
                            requireParam={['code']}
                            getData={params =>
                                dictionaryList(params).then(res => {
                                    if (res && res.code === 10000 && res.data) {
                                        return res.data || [];
                                    }
                                    return [];
                                })
                            }
                            fieldsName={{
                                selectValue: 'dictValue',
                                selectTitle: 'dictName'
                            }}
                            selectProps={{ placeholder: '请选择试用期' }}
                        />
                    )}
                </Form.Item>
            </FormContainer>
            <Row>
                <Col span={4}></Col>
                <Col span={20}>
                    {/* {checkCode('office:personnel:progress:entry:processentry') && ( */}
                    <Button
                        style={{ marginTop: 8 }}
                        htmlType="submit"
                        type="primary"
                        loading={loading.effects['entryDetail/saveEntry']}
                    >
                        提交
                    </Button>
                    {/* )} */}
                    {/* <Button
                        onClick={() => {
                            // form.resetFields();
                            // pageTabUtil.goBack();
                            history.push('/office/personnelManagement/onboardAndLeave/entryManagement');
                        }}
                    >
                        取消
                    </Button> */}
                </Col>
            </Row>
        </Form>
    );

    const renderEntryContent = () => {
        // eslint-disable-next-line react/no-danger
        const empty = <div dangerouslySetInnerHTML={{ __html: '&nbsp' }} />; // 要不然会换行？
        return (
            <Form {...formItemLayout} className={styles.detailForm}>
                <FormContainer>
                    <Form.Item label="员工姓名">{detail.employeeName || empty}</Form.Item>
                    <Form.Item label="员工工号">{detail.userNo || empty}</Form.Item>
                    {/* <Form.Item label="性别">{detail.sexTypeName || empty}</Form.Item> */}
                    <Form.Item label="手机号">{`+${detail.areaCode} ${detail.mobile}`}</Form.Item>
                    <Form.Item label="入职日期">
                        {typeof detail.entryDate !== 'object' && (detail.entryDate || empty)}
                    </Form.Item>
                    <Form.Item label="所属公司">{detail.companyName || empty}</Form.Item>
                    <Form.Item label="用户名">{detail.userName || empty}</Form.Item>
                    <Form.Item label="员工状态">{detail.inServiceStatusName || empty}</Form.Item>
                    <Form.Item label="员工邮箱">{detail.email || empty}</Form.Item>
                    <Form.Item label="部门">
                        {detail.departmentNames ? detail.departmentNames.join(' ') : empty}
                    </Form.Item>
                    <Form.Item label="角色">
                        {detail.roleNames ? detail.roleNames.map(item => <Tag>{item}</Tag>) : empty}
                    </Form.Item>
                    <Form.Item label="招聘职位">{detail.entryPostName || empty}</Form.Item>
                    <Form.Item label="招聘职级">{detail.employeeRank || empty}</Form.Item>
                    <Form.Item label="入职职位"> {detail.postNames ? detail.postNames.join(' ') : empty}</Form.Item>
                    <Form.Item label="入职职级"> {detail.postGradeCode || empty}</Form.Item>
                    <Form.Item label="带教人">{detail.teacher || empty}</Form.Item>
                    <Form.Item label="工作性质">{workNatureName || detail.workNatureName || empty}</Form.Item>
                    <Form.Item label="试用期">{detail.tryDurationName || empty}</Form.Item>
                </FormContainer>
            </Form>
        );
    };

    const content = editStatus ? renderOfferContent() : renderEntryContent();
    return (
        <PageHeaderWrapper>
            {editStatus ? (
                <Card bordered={false} bodyStyle={{ padding: '0 24px 24px' }}>
                    <div className={styles.headerCard}>
                        <h4>说明</h4>
                        <div>1.请在表格中录入用户名、员工邮箱、角色、合同签署状态和实际入职职位</div>
                        <div>2.可在此处修改员工的部分信息</div>
                        <div>3.提交后，员工工号、GMS初始账号、邮箱将自动生成</div>
                    </div>
                    <Card title="员工基本信息" bordered={false} className={styles.formHeaderCard}>
                        <Row>{content}</Row>
                    </Card>
                </Card>
            ) : (
                <Card
                    loading={loading.effects['entryDetail/getEntryDetail']}
                    title={`详情-${regionMap[detail.companyId] || ''}-${detail.employeeName || ''}`}
                    bordered={false}
                    className={styles.detailHeaderCard}
                >
                    <Row>{content}</Row>
                </Card>
            )}
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ loading, entryDetail }) => ({
        entryDetail,
        loading
    }))(Form.create()(AddEntry))
);
